<?php
class Frontend_Model_Category extends Custom_Model_Abstract
{
    /**
     * Find category by their id
     * @param int  $id
     * @return null|Wenda_Table_Row_Category
     */
    public function findById($id)
    {
        return Wenda::getTable('Category')->findById($id);
    }

    /**
     * Find parent of category by their id
     * @param int $id
     * @return null|Wenda_Table_Row_Category
     */
    public function findParentById($id)
    {
        return Wenda::getTable('Category')->findParentById($id);
    }

    /**
     * Find category by their parent id
     * @param int  $id
     * @return null|Zend_Db_Table_Rowset
     */
    public function findByParentId($id)
    {
        return Wenda::getTable('Category')->findByParentId($id);
    }

    /**
     * Get parentId = 0 all categories
     *
     * @return Zend_Db_Table_Rowset
     */
    public function getRoot()
    {
        return Wenda::getTable('Category')->findByParentId(0)->toArray();
    }

    /**
     * Get parents of tree
     *
     * @param int $id
     * @return null|array
     */
    public function getParents($id,$append = true)
    {
        $category = $this->findById($id);

        if (null === $category) {
            return null;
        }

        $cats = $append ? array($category->toArray()) : array();
        if (!$category->isRoot()) {
            $parent = $this->findParentById($id);
            $cats[] = $parent->toArray();
            $cats = array_merge($cats, $this->getParents($parent->id, false));
        }

        return $cats;
    }

    /**
     * Get children category by their id
     * @param int  $id
     * @return array
     */
    public function getChildren($id, $recursive = false)
    {
        $categories = $this->findByParentId($id);
        $cats = array();

        foreach ($categories as $category) {
            $cats[] = $category->toArray();
            if (true === $recursive) {
                $cats = array_merge($cats, $this->getChildren($category->id, true));
            }
        }

        return $cats;
    }

    /**
     * Get all categories
     * @return array
     */
    public function getAll()
    {
        $parents = $this->findByParentId(0);
        $cats = array();

        foreach ($parents as $category) {
            $cats[] = array_merge(
                $category->toArray(),
                array('subcategory'=>$this->getChildren($category->id))
            );
        }
        return $cats;
    }

    /**
     * Update scrore
     * @param int $id
     * @return boolean
     */
    public function updateScores($id)
    {
        $category = $this->findById($id);
        if (null !== $category) {
            $category->score = 1;
            return $category->save();
        }
        return false;
    }
}